from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from rest_framework.decorators import action
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView
from rest_framework import mixins
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status
from rest_framework.viewsets import GenericViewSet
from rest_framework_jwt.views import ObtainJSONWebToken

from .serializers import CreateUserSerializer, UserDetailSerializer, EmailSerializer, UserAddressSerializer, AddUserbrowsingHistorySerializer, AddressTitleSerializer
from .models import User
from . import constans
from goods.models import SKU
from goods.serializers import SKUSerializer
from carts.utils import merge_cart_cookie_to_redis


class UserAuthorizeView(ObtainJSONWebToken):

    """重写jwt_token认证类,目的为了让购物车合并,搭上帐号登录的顺风车"""

    def post(self, request, *args, **kwargs):

        response = super().post(request, *args, **kwargs)

        serializer = self.get_serializer(data=request.data)

        if serializer.is_valid():
            user = serializer.object.get('user') or request.user

            response = merge_cart_cookie_to_redis(request,user, response)
        return response


class AddUserBrowseHistoryView(CreateAPIView):

    #指定序列化器
    serializer_class = AddUserbrowsingHistorySerializer
    #指定权限
    permission_classes = [IsAuthenticated]


    def get(self, request):

        user_id = request.user.id

        redis_conn =  get_redis_connection('history')

        history = redis_conn.lrange('history_%s' %user_id, 0, -1)

        skus = []

        for sku_is in history:

            sku = SKU.objects.get(id=sku_is)

            skus.append(sku)

        s = SKUSerializer(skus, many=True)

        return Response(s.data)




class AddressViewSet(mixins.UpdateModelMixin, mixins.CreateModelMixin, GenericViewSet):
    """用户地址"""
    # 指定序列化器
    serializer_class = UserAddressSerializer
    # 指定权限
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    # GET /adresses/
    def list(self, request, *args, **kwargs):
        """获取用户所有地址"""

        queryset = self.get_queryset()

        serializer = self.get_serializer(queryset, many=True)

        user = self.request.user

        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': constans.USER_ADDRESS_COUNTS_LIMIT,
            'addresses': serializer.data,
        })

    # post /addresses/
    def create(self, request):
        # 新增地址

        # 获取用户保存的地址数量
        count = request.user.addresses.all().count()

        if count >= 20:
            return Response({'message': '用户地址超过上线'}, status=status.HTTP_400_BAD_REQUEST)

        # 创建序列化器进行返序列化
        serializer = self.get_serializer(data=request.data)
        # 校验
        serializer.is_valid(raise_exception=True)
        # 保存
        serializer.save()

        return Response(serializer.data)

    # delete /addresses/<pk>/
    def destroy(self, request, *args, **kwargs):
        """删除地址"""
        # 获取要删除的地址模型
        address = self.get_object()
        # 修改逻辑删除
        address.is_deleted = True
        # 保存
        address.save()

        return Response(status=status.HTTP_204_NO_CONTENT)

    # put /addresses/<pk>/status/
    @action(methods=['put'], detail=True)
    def status(self, request, pk=None):
        # 获取要设置为默认地址的地址模型对象
        address = self.get_object()
        # 修改用户默认地址
        request.user.default_address = address

        request.user.save()

        return Response({'message': 'OK'}, status=status.HTTP_200_OK)

    # put /addresses/<pk>/title/
    @action(methods=['put'], detail=True)
    def title(self, request, pk=None):
        """修改标题"""
        address = self.get_object()

        serialzer = AddressTitleSerializer(instance=address, data=request.data)

        serialzer.is_valid(raise_exception=True)

        serialzer.save()

        return Response(serialzer.data)


class VerifyEmailView(APIView):
    """邮箱验证"""

    def get(self, request):

        # 提取token
        token = request.query_params.get('token')
        if not token:
            return Response({'message': '缺少token'}, status=status.HTTP_400_BAD_REQUEST)

        # 校验token 是否是原来发送的数据
        user = User.check_verify_email_token(token)

        if not user:

            return Response({'message': '链接无效'}, status=status.HTTP_400_BAD_REQUEST)

        else:
            # 修改用户邮箱验证状态
            user.email_active = True
            user.save()

            return Response({'message': 'Ok'})


class EmailView(UpdateAPIView):
    """邮箱保存"""

    # 1 指定序列化器
    serializer_class = EmailSerializer
    # 指定视图权限(只有登录状态才能访问)
    permission_classes = [IsAuthenticated]

    # 重写get_object(self)方法手动给它指定用户

    def get_object(self):
        return self.request.user


# url(r'^user/$', views.UserDetailView.as_view())
class UserDetailView(RetrieveAPIView):
    """用户中心"""

    # 1指定序列化器
    serializer_class = UserDetailSerializer
    # 指定视图权限(只有登录状态才能访问)
    permission_classes = [IsAuthenticated]

    # 重写get_object(self)方法手动给它指定用户

    def get_object(self):
        return self.request.user


class UserView(CreateAPIView):
    """注册"""
    serializer_class = CreateUserSerializer


class UsernameCountView(APIView):
    """用户名数量"""

    def get(self, request, username):
        # 获取指定用户名数量
        count = User.objects.filter(username=username).count()

        data = {
            "username": username,
            "count": count
        }

        return Response(data)


class MobileCountView(APIView):
    """获取手机号数量"""

    def get(self, request, mobile):
        # 获取指定手机好数量
        count = User.objects.filter(mobile=mobile).count()

        data = {
            'mobile': mobile,
            'count': count
        }

        return Response(data)
